const { Component, _decorator } = cc;

const { ccclass, property } = _decorator;

@ccclass
export class SceneAsset extends Component {
    static assetDic = new Map<any, Map<string, any>>();
    @property([cc.Asset])
    assets: cc.Asset[] = [];
    @property([cc.Node])
    nodes: cc.Node[] = [];
    onLoad() {
        for (const asset of this.assets) {
            SceneAsset.addAsset(asset);
        }
        for (const node of this.nodes) {
            SceneAsset.addAsset(node);
        }
    }
    onDestroy() {
        SceneAsset.assetDic.clear();
    }
    public static addAsset(asset: cc.Asset | cc.Node) {
        let proto = Object.getPrototypeOf(asset);
        let assetMap = SceneAsset.assetDic.get(proto);
        if (!assetMap) {
            assetMap = new Map<string, cc.Asset | cc.Node>();
            SceneAsset.assetDic.set(proto, assetMap);
        }
        assetMap.set(asset.name, asset);
    }
    public static removeAsset<T extends cc.Asset | cc.Node>(actor: new () => T, asssetName: string) {
        let assetMap = SceneAsset.assetDic.get(actor.prototype);
        if (!assetMap) {
            assetMap = new Map<string, cc.Asset | cc.Node>();
            SceneAsset.assetDic.set(actor.prototype, assetMap);
        }
        assetMap.delete(asssetName);
    }
    public static getAsset<T>(actor: new () => T, asssetName: string) {
        let assetMap = SceneAsset.assetDic.get(actor.prototype);
        if (!assetMap) {
            assetMap = new Map<string, cc.Asset | cc.Node>();
            SceneAsset.assetDic.set(actor.prototype, assetMap);
        }
        return assetMap.get(asssetName) as T;
    }
}
